package com.design.adnroid.campussecondarytrading.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.design.adnroid.campussecondarytrading.AppContext;
import com.design.adnroid.campussecondarytrading.database.DBOperate;
import com.design.adnroid.campussecondarytrading.entity.Goods;
import com.design.adnroid.campussecondarytrading.entity.Person;

import java.util.ArrayList;

public class LoginActivity extends AppCompatActivity {

    private EditText etName, etPassWord;
    private Button btReg, btLogin;
    private CheckBox cbPWDdVisibility;

    private DBOperate dbOperate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle(getString(R.string.title_activity_login));

        etName = findViewById(R.id.login_name);
        etPassWord = findViewById(R.id.login_passWord);

        btReg = findViewById(R.id.login_reg);
        btLogin = findViewById(R.id.login_login);

        cbPWDdVisibility = (CheckBox) findViewById(R.id.login_checkBox);

        dbOperate = new DBOperate(this);

        ceshitianjia();//测试用,初始化数据库

        initPermissions();//初始化权限
        initEditText();//初始化EditText

        cbPWDdVisibility.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //如果选中，显示密码
                    etPassWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //否则隐藏密码
                    etPassWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        //        注册
        btReg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userRegister();
            }
        });//setOnClickListener

        //        登录
        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userLogin();
            }
        });

    }//onCreate

    private void initPermissions() {
        ArrayList permissions = new ArrayList();
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        permissions.add(Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS);

        //请求权限方法
        ActivityCompat.requestPermissions(LoginActivity.this,
                ((String[]) permissions.toArray(new String[permissions.size()])), 2);
    }

    private void initEditText() {
        Intent intent = getIntent();
        String uName = intent.getStringExtra("userName");
        String uPassWord = intent.getStringExtra("userPassword");
        if (uName == null && uPassWord == null) {
            etName.setText("root");
            etPassWord.setText("password");
            etName.setSelection(etName.getText().length());     //把光标设置到当前文本末尾
        } else {
            etName.setText(uName);
            etPassWord.setText(uPassWord);
        }
    }

    private void ceshitianjia() {
        dbOperate.openDB();
        Person person = new Person("root", "password", "第一", "男");
        dbOperate.addPerson(person);
        dbOperate.addPerson(new Person("admin", "admin123", "第二", "女"));
        //
        Bitmap bitmap[] = new Bitmap[5];
        int id[] = new int[]{R.mipmap.goods1, R.mipmap.goods2,
                R.mipmap.goods3, R.mipmap.goods4, R.mipmap.goods5};
        Goods goods[] = new Goods[5];
        String goodsId[] = new String[]{"goodsId1", "goodsId2", "goodsId3", "goodsId4", "goodsId5"};
        String goodsName[] = new String[]{"多肉", "花苗", "花卉盆栽苗", "园艺铲子", "园艺工具套装"};
        String goodsText[] = new String[]{"满19元包邮多肉植物组合盆栽含盆防辐射绿植园艺新手练手普货多肉",
                "玫瑰花苗杜鹃花天竺葵长寿花玫瑰海棠栀子花茉莉盆栽植物带花发货",
                "虹越园艺家爬藤本月季 粉龙 龙沙宝石1.5年嫁接6L花卉盆栽苗包邮",
                "沃施worth 园艺铲子 种花工具套装盆栽种菜栽花铲子小铲子三件套",
                "加厚种花工具家用小铲子养花种菜挖野菜铲子儿童铲子园艺工具套装"};
        String goodsTime[] = new String[]{"2018-04-19 15:32:59", "2018-03-19 13:35:49",
                "2017-12-19 20:32:02", "2018-02-25 07:54:36", "2018-02-18 03:04:16"};
        double goodsPrice[] = new double[]{1.0, 5.7, 108, 35.80, 20};
        String goodsOwner[] = new String[]{"admin", "root", "admin", "admin", "root"};
        String goodsOwnerContact[] = new String[]{"13939404058", "2987345656",
                "13461415066", "98765432101", "98765432101"};
        for (int i = 0; i < 5; i++) {
            bitmap[i] = BitmapFactory.decodeResource(getResources(), id[i]);
            goods[i] = new Goods(goodsId[i], goodsName[i], goodsText[i],
                    bitmap[i], goodsTime[i], goodsPrice[i],
                    goodsOwner[i], goodsOwnerContact[i]);
            dbOperate.addGoods(goods[i]);
        }
        dbOperate.closeDb();
    }

    private void userRegister() {
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), RegisterActivity.class);
        startActivity(intent);
    }

    private void userLogin() {
        String userName = etName.getText().toString();
        String userPassWord = etPassWord.getText().toString();
        if (userName.isEmpty()) {
            etName.requestFocus();
            etName.setError(getString(R.string.a_login_userNameEmptyError));
            return;
        }
        if (userPassWord.isEmpty()) {
            etPassWord.requestFocus();
            etPassWord.setError(getString(R.string.a_login_userPwdEmptyError));
            return;
        }

        dbOperate.openDB();
        boolean flag0 = dbOperate.findPerson(userName, userPassWord);
        boolean flag1 = dbOperate.havePerson(userName);
        Person person = dbOperate.getPerson(userName);
        dbOperate.closeDb();

        if (flag0) {//登录成功
            AppContext.setUserName(person.getUserName());
            AppContext.setName(person.getName());
            AppContext.setUserMd5(person.getUserMd5());

            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            if (flag1) {//账户存在,登录失败
                etPassWord.requestFocus();
                etPassWord.setError(getString(R.string.a_login_userPwdError));
                Toast.makeText(getApplicationContext(), "密码错误！", Toast.LENGTH_SHORT).show();
            } else {
                etName.requestFocus();
                etName.setError(getString(R.string.a_login_noUserNameError));
                Toast.makeText(getApplicationContext(), "账户不存在！", Toast.LENGTH_SHORT).show();
            }//if-else
        }//if-else
    }

}
